#!/usr/bin/env python
# -*- coding:utf8 -*-
import sys,os
import pickle
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.append(BASE_DIR)

from conf import settings
from lib import uid


class BaseClass(object):
    """基础类"""

    def save_file(self, role_type, dic):
        """
        保存文件
        :param role_type:
        :param dic:
        :return:
        """
        filename = uid.create_md()
        dic['uid'] = filename
        file_path = "%s\%s" % (settings.db_DIR, role_type)
        ab_file = '%s\%s' % (file_path, filename)
        if os.path.isdir(file_path):
            with open(ab_file, 'wb') as f:
                # f.write(pickle.dumps(dic))
                pickle.dump(dic, f)
                if True:
                    print("创建成功")
                    for i in dic:
                        print(i, dic[i], end="\n")

    def seek_list(self, role_type, li):
        filename = uid.create_md()
        file_path = os.path.join(settings.db_DIR, role_type)
        ab_file = os.path.join(file_path, filename)
        if os.path.isdir(file_path):
            with open(ab_file, 'wb') as f:
                pickle.dump(li, f)
                if True:
                    print("创建成功")
                    for i in li:
                        for key in i:
                            print(key, i[key], end='\n')
        return True

    def open_file(self, role_type):
        """
        打开文件
        :param role_type:
        :return:
        """
        all_data = []
        db_path = "%s/%s" % (settings.db_DIR, role_type)
        for i in os.listdir(db_path):
            if os.path.isfile(os.path.join(db_path, i)) and i != "__init__.py":
                db_file = os.path.join(db_path, i)
                with open(db_file, "rb") as f:
                    file_dict = pickle.load(f)
                    all_data.append(file_dict)
        return all_data

